<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam" :data-callback="dataCallback">
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button v-auth="'employee_index_save'" type="primary" :icon="CirclePlus" @click="openDrawer('新增')">
          新增员工
        </el-button>
        <el-button
          v-auth="'employee_index_remove'"
          type="danger"
          :icon="Delete"
          plain
          :disabled="!scope.isSelected"
          @click="batchDelete(scope.selectedListIds.map(Number))"
        >
          批量删除员工员工
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)"> 查看 </el-button>
        <el-button v-auth="'employee_index_save'" type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">
          编辑
        </el-button>
        <el-button v-auth="'employee_index_rest_password'" type="primary" link :icon="Refresh" @click="resetPass(scope.row)">
          重置密码
        </el-button>
        <el-button v-auth="'employee_index_remove'" type="primary" link :icon="Delete" @click="oneDelete(scope.row)">
          删除
        </el-button>
        <el-button v-auth="'employee_index_set_status'" type="primary" link :icon="EditPen" @click="changeStatus(scope.row)">
          {{ scope.row.status === 1 ? "禁用" : "启用" }}
        </el-button>
      </template>
    </ProTable>
    <EmployeeDrawer ref="drawerRef" />
  </div>
</template>

<script setup lang="tsx" name="employeeIndex">
import { ref, reactive, onMounted } from "vue";
import { Employee, Role } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import EmployeeDrawer from "@/views/system/employee/components/EmployeeDrawer.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, View, Refresh } from "@element-plus/icons-vue";
import { ElNotification } from "element-plus";
import { getEmployeeList, saveEmployee, deleteEmployee, setEmployeeStatus, resetEmployeePassword } from "@/api/modules/employee";
import { genderType, employeeStatus } from "@/utils/dict";
import { EnumProps } from "@/components/ProTable/interface/index";
import { getRoleList } from "@/api/modules/role";

const roleList = ref<EnumProps[]>([]);
onMounted(async () => {
  // 加载角色列表
  const res = await getRoleList({ name: "" });
  res.data.forEach((item: Role.ResRoleList) => {
    roleList.value.push({
      value: item.id,
      label: item.name
    });
  });
});
// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.list,
    total: data.total
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  delete newParams.createTime;
  return getEmployeeList(newParams);
};

// 表格配置项
const columns = reactive<ColumnProps<Employee.ResEmployeeList>[]>([
  { type: "selection", fixed: "left", width: 70 },
  {
    prop: "name",
    fixed: "left",
    label: "姓名",
    search: { el: "input" },
    width: 100
  },
  {
    prop: "status",
    label: "员工状态",
    enum: employeeStatus,
    width: 100,
    search: { el: "select", props: { filterable: true } },
    render: scope => {
      return (
        <>{<el-tag type={scope.row.status === 1 ? "success" : "danger"}>{scope.row.status === 1 ? "启用" : "禁用"}</el-tag>}</>
      );
    }
  },
  {
    prop: "phone",
    label: "手机号",
    width: 130
  },
  {
    prop: "gender",
    label: "性别",
    // 字典数据（本地数据）
    enum: genderType,
    width: 70
  },
  { prop: "idCard", label: "身份证号", width: 190 },
  { prop: "brithday", label: "生日", width: 120 },
  { prop: "chineseZodiac", label: "属相", width: 70 },
  {
    prop: "height",
    label: "身高",
    width: 90,
    render: scope => {
      return <>{scope.row.height == null ? "--" : scope.row.height + " CM"} </>;
    }
  },
  {
    prop: "weight",
    label: "体重",
    width: 90,
    render: scope => {
      return <>{scope.row.weight == null ? "--" : scope.row.weight + " KG"} </>;
    }
  },
  {
    prop: "workYear",
    label: "工作经验",
    width: 130,
    render: scope => {
      return <>{scope.row.workYear == null ? "--" : scope.row.workYear + " 年工作经验"} </>;
    }
  },
  {
    prop: "registeredResidence",
    label: "户籍地",
    width: 130
  },
  {
    prop: "educational",
    label: "学历",
    width: 90
  },
  {
    prop: "roleIds",
    label: "员工角色",
    width: 260,
    enum: roleList,
    search: { el: "select", props: { filterable: true, multiple: true, collapseTags: true } },
    render: scope => {
      return (
        <>
          {scope.row.roleNames.length == 0
            ? "--"
            : scope.row.roleNames.map((roleName: string) => (
                <el-tag type="primary" style="margin:0px 4px;">
                  {roleName}
                </el-tag>
              ))}
        </>
      );
    }
  },
  { prop: "address", label: "居住地址", width: 300 },
  {
    prop: "createTime",
    label: "创建时间",
    width: 120
  },
  { prop: "operation", label: "操作", fixed: "right", width: 400 }
]);

// 删除员工信息
const oneDelete = async (params: Employee.ResEmployeeList) => {
  const reqParams: Employee.ReqEmployeeDeleteParams = {
    id: [params.id]
  };
  await useHandleData(deleteEmployee, reqParams, `删除【${params.name}】员工`);
  proTable.value?.getTableList();
};

// 批量删除员工信息
const batchDelete = async (id: number[]) => {
  const reqParams: Employee.ReqEmployeeDeleteParams = {
    id: id
  };
  await useHandleData(deleteEmployee, reqParams, "删除所选员工信息");
  proTable.value?.clearSelection();
  proTable.value?.getTableList();
};

// 重置员工密码
const resetPass = async (params: Employee.ResEmployeeList) => {
  const reqParams: Employee.ReqEmployeeResetPasswordParams = {
    id: params.id
  };
  const res = await useHandleData(resetEmployeePassword, reqParams, `重置【${params.name}】员工密码`);
  ElNotification({
    title: `重置【${params.name}】员工密码成功`,
    message: `新密码: ${res.data}，已发送到员工手机号`,
    type: "success"
  });
  proTable.value?.getTableList();
};

// 切换员工状态
const changeStatus = async (row: Employee.ResEmployeeList) => {
  const reqParams: Employee.ReqEmployeeStatusParams = {
    id: row.id,
    status: row.status == 1 ? 0 : 1
  };
  await useHandleData(setEmployeeStatus, reqParams, `设置【${row.name}】员工状态`);
  proTable.value?.getTableList();
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof EmployeeDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<Employee.ResEmployeeList> = {}) => {
  if (row.avatarUrl == null) row.avatarUrl = "";
  const params = {
    title,
    isView: title === "查看",
    row: { ...row, FileList: row.photoUrls },
    api: title === "新增" ? saveEmployee : title === "编辑" ? saveEmployee : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};
</script>
